<?php

/**
 * Project:     Rebel PHP Framework
 * File:        Db.php
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * @link http://www.rebelphpframework.org
 * @copyright 2007 Emanuele Colonnelli
 * @author Emanuele Colonnelli <emanuele.colonnelli at gmail dot com>
 * @package kernel
 * @version 1.0
 */

namespace org\phpstruct\db\PDO;


use org\phpstruct\core;
use org\phpstruct\db;
use org\phpstruct\db\I;

if (define(__CLASS__, true)) {


  class Db  {

	private static $instance;
	/**
	 * Rebel_Config_Rebel_Config_XMLConfig object
	 *
	 * @var Rebel_Config_XMLConfig
	 */
	private static $xcfg;
	/**
	 * PDO Connection handler
	 *
	 * @var PDO
	 */
	private static $dbh;
	public static $DRIVER_NAME = null;

	public function __construct() {
	  try {
		self::$xcfg = Rebel_Config_XMLConfig::getInstance();
		\preg_match("~^(oci):~", self::$xcfg->{"database.dsn"}, $ret);

		self::$DRIVER_NAME = $ret[1];

		if ($ret[1] == 'oci') {
		  $tns = str_replace('oci:dbname=', '', self::$xcfg->{"database.dsn"});
		  self::$dbh = @\oci_connect(self::$xcfg->{'database.username'}, self::$xcfg->{'database.password'}, $tns, self::$xcfg->{"database.charset"});
		  if (!self::$dbh) {
			$arrayError = error_get_last();
			throw new Exception($arrayError["message"]);
		  }
		} else {

		  self::$dbh = new \PDO(self::$xcfg->{"database.dsn"}, self::$xcfg->{"database.username"}, self::$xcfg->{"database.password"});
		  self::$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		  self::$dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
		}
		self::$instance = $this;
	  } catch (Exception $e) {
		die('DATABASE ERROR');
	  }
	}

//:-

	/**
	 * @return PDO
	 */
	public static function getInstance() {
	  return self::$instance ? self::$instance : new self;
	}

//:-

	public function __call($func, $args) {
	  $d = self::$dbh;



	  if (!@call_user_func_array(array($d, $func), $args)) {
		$err = error_get_last();
		throw new Exception('ERROR CALLING: ' . $func . ' ' . $err['message'], $err['type']);
	  }
	}

	public function getAttribute($attribute) {

	  try {

		if ('oci' == self::$DRIVER_NAME) {

		  if ($attribute == PDO::ATTR_DRIVER_NAME) {
			return self::$DRIVER_NAME;
		  } else {
			return null;
		  }
		} else {
		  return self::$dbh->getAttribute($attribute);
		}
	  } catch (Exception $e) {
		throw $e;
	  }
	}

//

	public function commit() {

	  try {
		if ('oci' == self::$DRIVER_NAME) {
		  return oci_commit(self::$dbh);
		} else {
		  return self::$dbh->commit();
		}
	  } catch (Exception $e) {
		throw $e;
	  }
	}

//

	public function setAttribute($attribute, $value) {

	  if ('oci' != self::$DRIVER_NAME) {
		return self::$dbh->setAttribute($attribute, $value);
	  }
	}

//

	public function prepare($sql) {

	  try {

		switch (self::$DRIVER_NAME) {
		  case 'oci':

			$stmt = oci_parse(self::$dbh, $sql);

			$ret = new Rebel_DB_PDO_PDOStatement();
			$ret->stmt = $stmt;

			return $ret;
			break;
		  default:
		  case 'mysql':
			return self::$dbh->prepare($sql);
			break;
		}
	  } catch (Exception $e) {
		throw $e;
	  }
	}

//

	public function query($query) {
	  try {

		if ('oci' == self::$DRIVER_NAME) {

		  $oci_stmt = oci_parse(self::$dbh, $query);

		  if ($stmt = @oci_execute($oci_stmt)) {
			$rs = array();
			while ($row = oci_fetch_array($oci_stmt, OCI_ASSOC)) {
			  array_push($rs, $row);
			}

			oci_free_cursor($oci_stmt);

			return $rs;
		  } else {
			$err = oci_error(self::$dbh);
			throw new Exception($err['message'] . $err['sqltext'], $err['code']);
		  }
		} else {
		  return self::$dbh->query($query);
		}
	  } catch (Exception $e) {
		throw $e;
	  }
	}

//

	public function exec($query) {

	  try {

		if ('oci' == self::$DRIVER_NAME) {

		  throw new Exception('PDO::exec FOR ORACLE NOT YET IMPLEMENTED IN REBEL');
		} else {
		  return self::$dbh->exec($query);
		}
	  } catch (Exception $e) {
		throw $e;
	  }
	}

//

	public function quote($string, $parameter_type=null) {

	  try {

		if ('oci' != self::$DRIVER_NAME) {
		  return self::$dbh->quote($string, $parameter_type);
		} else {
		  return "'$string'";
		}
	  } catch (Exception $e) {
		throw $e;
	  }
	}

//

	public static function validateQuery(PDOStatement &$stmt) {

	  if (!$stmt->execute()) {
		$err = $stmt->errorInfo();
		throw new Exception($err[2], $err[1]);
	  }
	}

//:-

	/**
	 * WORK IN PROGESS
	 *
	 * Call execute Method of PDOStatement, accepts a hash with :param_name => value and
	 * a fetchType param:
	 * null => no Fetch ( use this for insert update delete ) returns a boolean
	 * object => returns an array of record objects
	 * all => returns all records as associative array
	 *
	 * @param String $query
	 * @param Array $boundParams
	 * @param Mixed $fetchMode
	 */
	public function improvedExecute($query, $boundParams=array(), $fetchMode=null) {

	  $stmt = self::$instance->prepare($query);
	  if (0 < count($boundParams)) {
		foreach ($boundParams as $v) {
		  $stmt->bindParam(':$k', $v);
		}
	  }
	  if (!$stmt->execute()) {
		$err = $stmt->errorInfo();
		throw new Exception($err[2], $err[1]);
	  }

	  return $stmt->fetchAll($fetchMode ? $fetchMode : PDO::FETCH_ASSOC);
	}

//:-

	public function beginTransaction() {
	  try {
		if ('oci' == self::$DRIVER_NAME) {

		  //$stmt = oci_parse(self::$dbh,'BEGIN');
		  //return oci_execute($stmt);
		  return true;
		} else {
		  return self::beginTransaction();
		}
	  } catch (Exception $e) {
		throw $e;
	  }
	}

//

	public function rollBack() {
	  try {
		if ('oci' == self::$DRIVER_NAME) {
		  return oci_rollback(self::$dbh);
		} else {
		  return self::rollBack();
		}
	  } catch (Exception $e) {
		throw $e;
	  }
	}

	public function createLobDescriptor() {
	  try {
		if ('oci' == self::$DRIVER_NAME)
		  return oci_new_descriptor(self::$dbh, OCI_D_LOB);

		return false;
	  } catch (Exception $e) {
		throw $e;
	  }
	}

	public function uploadOnBlob($lobDescriptor, $lob_upload) {
	  try {
		if ('oci' == self::$DRIVER_NAME)
		  $lobDescriptor->savefile($lob_upload);
		self::commit();

		return false;
	  } catch (Exception $e) {
		throw $e;
	  }
	}

	public function freeLobDescriptor($lobDescriptor) {
	  try {
		if ('oci' == self::$DRIVER_NAME)
		  return oci_free_descriptor($lobDescriptor);

		return false;
	  } catch (Exception $e) {
		throw $e;
	  }
	}

  }

}